package net.youpo.Market.UI;

import net.youpo.Market.MarketApplication;
import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.Service.MessageService;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.DeviceInfo;
import net.youpo.Market.Util.GlobalVariables;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

public class Loading extends Activity {
    private final int LOADING_ANIM = 0;// 动画
    private final int SUCCESS = 1;// 初始化完成
    private final int UPDATE_PROGRESS = 2;// 更新进度
    private final int NETWORK_TIPS = 3;// 网络提示
    private final String REQS_CONFIG = "config/";
    private int position = 0;// 动画的位置
    private HttpConnection mHttpConn;
    private int mPosition = 0;// 进度百分比
    private long mUseTimes = 0;// 本软件使用次数
    private int newVerCode;// 新版本号
    private String newVerUrl;// 新版本地址
    private String newVerDesc;// 新版本描述
    private boolean needUpdate = false;
    private ImageView[] loadingArr = new ImageView[4];
    private int[] loadingResArr = { R.id.loading_01, R.id.loading_02,
            R.id.loading_03, R.id.loading_04 };
    private long startTime;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);
        if (GlobalVariables.IS_RUNNING) {
            mHandler.sendEmptyMessage(SUCCESS);
            return;
        }
        startTime = System.currentTimeMillis();
        GlobalVariables.IS_RUNNING = true;
        initUI();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                saveUseTimes();// 记录使用次数
                checkNetState();// 检查网络状态
                if (GlobalVariables.network_state > 0) {// 如果有网络
                    mHttpConn = new HttpConnection();
                    getMarketSetting();// 从服务器获得默认设置项
                    checkMarketVerson();// 检查当前版本是否需要升级
                    getInstallApp();
                    getAppUpdateInfo();
                    getHomepageBanner();
                    getHomepageRecommendApp();
                    startMessageService();// 开启后台消息推送service
                    long nowTime = System.currentTimeMillis();
                    if (nowTime - startTime < 3000) {
                        try {
                            Thread.sleep(3000 - (nowTime - startTime));
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.sendEmptyMessage(SUCCESS);
                }
                mPosition = 100;
            }
        });
        thread.setName("LoadingThread");
        thread.start();
    }

    private void initUI() {
        for (int n = 0; n < 4; n++) {
            loadingArr[n] = (ImageView) findViewById(loadingResArr[n]);
        }
        mHandler.sendEmptyMessage(LOADING_ANIM);
    }

    /**
     * 开启消息服务
     */
    private void startMessageService() {
        Intent intent = new Intent(Loading.this, MessageService.class);
        startService(intent);
    }

    /**
     * 记录使用次数
     */
    private void saveUseTimes() {
        SharedPreferences sPreferences = PreferenceManager
                .getDefaultSharedPreferences(Loading.this);
        mUseTimes = sPreferences.getLong(ConstantsTable.USE_TIMES, 0);
        SharedPreferences.Editor editor_isstop = sPreferences.edit();
        editor_isstop.putLong(ConstantsTable.USE_TIMES, ++mUseTimes);
        if (mUseTimes == 1 && !hasShortcut(Loading.this)) {// 第一次且桌面没有该图标
            editor_isstop.putLong(ConstantsTable.INSTALL_TIME,
                    System.currentTimeMillis());
            createIconOnLauncher();// 创建快捷图标
        }
        editor_isstop.commit();
    }

    /**
     * 检查网络状态
     */
    private void checkNetState() {
        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        final String CONNECTED = "CONNECTED";// 链接状态

        // wifi
        State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                .getState();
        if (wifi.toString().equals(CONNECTED)) {// wifi连接状态
            GlobalVariables.network_state = 2;
            mHandler.sendEmptyMessage(NETWORK_TIPS);
            return;// 优先wifi
        }

        // mobile 3G Data Network
        State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
                .getState();
        if (mobile.toString().equals(CONNECTED)) {// 3G网络连接状态
            GlobalVariables.network_state = 1;
        }
        mHandler.sendEmptyMessage(NETWORK_TIPS);
    }

    /**
     * 获得市场的默认设置项
     */
    private void getMarketSetting() {
        String resultJson = mHttpConn.requestService(REQS_CONFIG, new String[] {
                ConstantsTable.KEY_VC, ConstantsTable.NOW_VERSION,
                ConstantsTable.KEY_IMEI, ConstantsTable.IMEI });

        JSONObject person = null;
        try {
            JSONTokener jsonParser = new JSONTokener(resultJson);
            person = (JSONObject) jsonParser.nextValue();
            newVerCode = person.getInt("ver");// 获取新版本号
            newVerUrl = person.getString("dlurl");// 新版本地址
            newVerDesc = person.getString("udesc");// 新版本描述
        } catch (JSONException e) {// 如果没有新版本升级就会报这个异常
            Log.e(ConstantsTable.LOG_TAG, "Loading config json error");
            e.printStackTrace();
        } finally {
            try {
                if (person != null) {
                    GlobalVariables.DATA_REFRESH_TIME = person.getInt("phti");// 推荐请求时间
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        // Log.d("H3c", newVerCode + "-" + newVerUrl + "-"
        // + GlobalVariables.RECOMMEND_REFRESH_TIME);
    }

    /**
     * 检查市场的版本
     */
    private void checkMarketVerson() {
        if (newVerCode > Integer.valueOf(ConstantsTable.NOW_VERSION)) { // 如果有新版
            needUpdate = true;
        }
    }

    /**
     * 获取首页的Banner信息
     */
    private void getHomepageBanner() {

    }

    /**
     * 获取首页推荐应用信息
     */
    private void getHomepageRecommendApp() {

    }

    private void getInstallApp() {
        GlobalVariables.ALL_INSTALL_APP.clear();
        GlobalVariables.ALL_INSTALL_APP = DeviceInfo.getInstallAppInfo();
    }

    /**
     * 获取应用升级信息
     */
    private void getAppUpdateInfo() {
        StringBuffer sb = new StringBuffer();
        sb.append(ConstantsTable.KEY_VC + ConstantsTable.NOW_VERSION + "&imei="
                + ConstantsTable.IMEI + "&packages=");
        for (AppInfoBean appinfo : GlobalVariables.ALL_INSTALL_APP) {
            sb.append(appinfo.APP_PACK + ":" + appinfo.APP_VER + ";");
        }

        HttpConnection hc = new HttpConnection();
        String resultJson = hc.requestService2("Apps/CheckVersion", sb);
        getJsonData(resultJson);
    }

    private void getJsonData(String json) {
        JSONObject jsonObject;
        PackageManager pm = MarketApplication.getMarketAppContext()
                .getPackageManager();
        try {
            jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("uds");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject2 = (JSONObject) jsonArray.opt(i);
                AppInfoBean mAppBean = new AppInfoBean();
                mAppBean.APP_ID = jsonObject2.getString("id");
                mAppBean.APP_PACK = jsonObject2.getString("pn");
                mAppBean.APP_URL = jsonObject2.getString("dl");
                PackageInfo packageInfo = pm.getPackageInfo(mAppBean.APP_PACK,
                        0);
                mAppBean.APP_NAME = packageInfo.applicationInfo.loadLabel(pm)
                        .toString();
                mAppBean.APP_ICON_BMP = packageInfo.applicationInfo
                        .loadIcon(pm);
                mAppBean.APP_VER = packageInfo.versionCode;
                GlobalVariables.NEED_UPDATE_APP
                        .put(mAppBean.APP_NAME, mAppBean);
            }
            GlobalVariables.UPDATE_NUM = GlobalVariables.NEED_UPDATE_APP.size();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 在桌面上创建图标
     */
    private void createIconOnLauncher() {
        Intent shortcut = new Intent(
                "com.android.launcher.action.INSTALL_SHORTCUT");

        // 快捷方式的名称
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME,
                getString(R.string.app_name));
        shortcut.putExtra("duplicate", false); // 不允许重复创建

        // 指定当前的Activity为快捷方式启动的对象: 如 com.everest.video.VideoPlayer
        // 注意: ComponentName的第二个参数必须加上点号(.)，否则快捷方式无法启动相应程序
        ComponentName comp = new ComponentName(this.getPackageName(), "."
                + this.getLocalClassName());
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(comp);
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);

        // 快捷方式的图标
        ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(
                this, R.drawable.icon);
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);

        sendBroadcast(shortcut);
    }

    /**
     * 判断桌面上是否有的快捷方式
     * 
     * @return
     */
    private boolean hasShortcut(Context context) {
        final ContentResolver cr = context.getContentResolver();
        final String AUTHORITY = "com.android.launcher2.settings";
        final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
                + "/favorites?notify=true");
        Cursor c = cr.query(CONTENT_URI, new String[] { "intent" }, null, null,
                null);
        if (c == null) {
            return false;
        }
        while (c.moveToNext()) {
            String intentstring = c.getString(c.getColumnIndex("intent"));
            if (intentstring == null) {
                continue;
            }
            String componentString = getComponentString(intentstring);
            if (componentString.startsWith(context.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    private String getComponentString(String intentInfo) {
        // intent info
        // 的格式:intent=#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10200000;component=com.allstar.tanzhi/.activities.StartActivity;end
        int start = intentInfo.indexOf("component") + 9 + 1;
        int end = intentInfo.indexOf(";", start);
        return intentInfo.substring(start, end);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case LOADING_ANIM: {
                int n = position % 4;
                if (n == 0) {
                    loadingArr[3].setImageResource(R.drawable.loading_dark);
                } else {
                    loadingArr[n - 1].setImageResource(R.drawable.loading_dark);
                }
                loadingArr[n].setImageResource(R.drawable.loading_light);
                position++;
                postDelayed(mAnim, 500);
                break;
            }
            case SUCCESS: {// 加载完成页面跳转
                Intent intent = new Intent(Loading.this, MainActivity.class);
                intent.putExtra("need_update", needUpdate);
                newVerUrl = "http://gdown.baidu.com/data/wisegame/ad1737e254fa2b8a/anzhuoshichang.apk";
                intent.putExtra("url", newVerUrl);
                startActivity(intent);
                mHandler.removeCallbacks(mAnim);
                Loading.this.finish();
                break;
            }
            case UPDATE_PROGRESS: {// 更新进度条
                break;
            }
            case NETWORK_TIPS: {// 网络提示
                int stringID = R.string.null_network_tips;
                if (GlobalVariables.network_state == 1) {// 移动网络
                    stringID = R.string.gprs_tips;
                } else if (GlobalVariables.network_state == 2) {// wifi网络
                    stringID = R.string.wifi_tips;
                }

                Toast.makeText(Loading.this, stringID, Toast.LENGTH_SHORT)
                        .show();
                if (0 == GlobalVariables.network_state) {
                    postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Loading.this.finish();
                            System.exit(0);
                        }
                    }, 1500);
                }
                break;
            }
            default:
            }
        }
    };

    Runnable mAnim = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(LOADING_ANIM);
        }
    };
}